﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Nextensions.Text
{
    public class MLUtil
    {
        public static string GetAttributeValue(string HTML, string AttributeName)
        {
            // This regex captures attribute values with or without quotes. It uses a conditional match statement that searches for non quote values if quotes are found, or non-whitespace values if no quotes are found. I created it and tested it outside this application, so i just need to implement and test it here. Also, i need to add support for single quotes:
            // <option\s+[^\>]*value\s*=(?<q>\")?(?<val>(?(q)[^\"]+|[^\s\>]+))
            Match m = Regex.Match(HTML, String.Format(@"\s{0}\s*=\s*(\""(?<dq>[^\""]*)\""|'(?<sq>[^']*)'|(?<nonWS>[^\s>]+))", AttributeName), RegexOptions.IgnoreCase);

            if (!m.Success)
                return null;

            string val;

            if(m.Groups["dq"].Success)
                val =  m.Groups["dq"].Value;
            else if(m.Groups["sq"].Success)
                val = m.Groups["sq"].Value;
            else
                val = m.Groups["nonWS"].Value;

            return val;
        }

        public static List<string> GetNodeText(string ML, string NodeName)
        {
            return GetNodeText(ML, NodeName, true);
        }

        public static List<string> GetNodeText(string ML, string NodeName, bool RequiresClosing)
        {
            List<string> elements;

            string tagContent = String.Format(@"(?<content>(?:.(?!</{0}))+.)</{0}>", NodeName);
            string tag = String.Format(@"<{0}(?=\s|>)(\w+\s*=\s*\""[^\""]*\""|[^>])*?/?>{1}", NodeName, (RequiresClosing ? tagContent : ""));
            MatchCollection matches = Regex.Matches(ML, tag, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

            elements = new List<string>(matches.Count);

            for (int i = 0; i < matches.Count; i++)
                elements.Add(matches[i].Value);

            return elements;
        }
    }
}
